import java.net.*;
import java.io.*;
public class echoserver {

	/**
	 * @param args
	 */
	protected Socket Client;
	
	public static void main(String[] args) throws IOException{
		
		ServerSocket serverSocket = null;
		
        try{
            serverSocket = new ServerSocket(Integer.parseInt("35800"));
        	while(true)
        	{
        		System.out.println("Dang cho client");
        		new echoserver(serverSocket.accept());     
        	}
            
        } catch (IOException e) {
            System.out.println("Exception caught when trying to listen on port "
                + 35800 + " or listening for a connection");
            System.out.println(e.getMessage());
        }
        finally
        {
         try {
              serverSocket.close(); 
             }
         catch (IOException e)
             { 
              System.err.println("Could not close port:35800 ."); 
              System.exit(1); 
             } 
        }
	}
	
	public String GetName(String message)
	{
		String name = message.substring(0, message.indexOf(':'));
		return name;
	}
	
	public echoserver(Socket clientsocket)
	{
		Client = clientsocket;
		Start();
	}
	
	public void Start()	                                     
	{
		System.out.println ("New Communication Thread Started");

	    try 
	    { 
	         PrintWriter out = new PrintWriter(Client.getOutputStream(), true); 
	         BufferedReader in = new BufferedReader(new InputStreamReader( Client.getInputStream())); 
	         String inputLine; 

	         while ((inputLine = in.readLine()) != null) 
	         { 
	              System.out.println (inputLine); 
	              out.println(inputLine); 

	              if (inputLine.equals("bye")) 
	                  break; 
	          } 

	         out.close(); 
	         in.close(); 
	         Client.close(); 
	    } 
	    catch (IOException e) 
	    { 
	         System.err.println("Problem with Communication Server");
	         System.exit(1); 
	    } 
	}

}
